package com.microframework.boot.collect.model.dev;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.cookie.BasicCookieStore;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.client5.http.impl.cookie.BasicClientCookie;
import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.apache.hc.core5.ssl.SSLContextBuilder;

import com.alibaba.fastjson2.JSONObject;
import com.jfinal.kit.JsonKit;

import javax.net.ssl.SSLContext;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.Date;

public class HttpClientWithCookieAuth {

    private static final String TARGET_URL = "https://220.163.82.253:5321/yth-api/wkkfm-nmine/wkkUndermineSubstationInfo/getWkkUndermineSubstationInfoList";
    private static final String AUTH_TOKEN = "27c346ca-8509-419e-87c1-812ee6469818";
    private static final String VERIFICATION_COOKIE = "cf2a061e-96f7-464a-a789-febfb3c25c0d";
    private static final String DOMAIN = "220.163.82.253";

    public static void main(String[] args) {
        try {
            CloseableHttpClient httpClient = createAuthenticatedClient();
            
            JSONObject params = new JSONObject();
            params.put("current", 1);
            params.put("size", 10);
            params.put("mineCode", "530402000001");
            
            HttpPost httpPost = new HttpPost(TARGET_URL);
            httpPost.setEntity(new StringEntity(JsonKit.toJson(params), ContentType.APPLICATION_JSON));
            
            // 设置所有必要的请求头
            setRequestHeaders(httpPost);
            
            System.out.println("Sending request to: " + TARGET_URL);
            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                System.out.println("Response status: " + response.getCode());
                String responseBody = EntityUtils.toString(response.getEntity());
                System.out.println("Response body: " + responseBody);
            }
        } catch (Exception e) {
            System.err.println("Error during request: " + e.getMessage());
            e.printStackTrace();
        }
    }

    private static CloseableHttpClient createAuthenticatedClient() 
            throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
        
        // 1. 创建并配置Cookie存储
        BasicCookieStore cookieStore = new BasicCookieStore();
        BasicClientCookie cookie = new BasicClientCookie("verification_error_count", VERIFICATION_COOKIE);
        cookie.setDomain(DOMAIN);
        cookie.setPath("/");
        cookie.setSecure(true);
        cookie.setExpiryDate(new Date(System.currentTimeMillis() + 86400000)); // 1天后过期
        cookieStore.addCookie(cookie);

        // 2. 配置SSL（信任所有证书，仅用于测试）
//        SSLContext sslContext = SSLContextBuilder.create()
//                .loadTrustMaterial((chain, authType) -> true)
//                .build();

        // 3. 创建HttpClient
        return HttpClients.custom()
                .setDefaultCookieStore(cookieStore)
               // .setSSLContext(sslContext)
                .build();
    }

    private static void setRequestHeaders(HttpPost httpPost) {
        // 设置所有必要的请求头
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Accept-Encoding", "gzip, deflate, br");
        httpPost.setHeader("Accept-Language", "zh-CN,zh;q=0.9");
        httpPost.setHeader("Authorization", "Bearer " + AUTH_TOKEN);
        httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
        httpPost.setHeader("Origin", "https://220.163.82.253:5321");
        httpPost.setHeader("Referer", "https://220.163.82.253:5321/largeScreen/underground/company");
        httpPost.setHeader("Sec-Ch-Ua", "\"Not)A;Brand\";v=\"8\", \"Chromium\";v=\"138\", \"Google Chrome\";v=\"138\"");
        httpPost.setHeader("Sec-Ch-Ua-Mobile", "?0");
        httpPost.setHeader("Sec-Ch-Ua-Platform", "\"Windows\"");
        httpPost.setHeader("Sec-Fetch-Dest", "empty");
        httpPost.setHeader("Sec-Fetch-Mode", "cors");
        httpPost.setHeader("Sec-Fetch-Site", "same-origin");
        httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36");
        httpPost.setHeader("Priority", "u=1, i");
        httpPost.setHeader("Locale", "zh-CN");
    }
}